package com.cecsmsserve.controller;


import com.cecsmsserve.entity.User;
import com.cecsmsserve.service.IUserService;
import com.cecsmsserve.util.result.CommonResult;
import com.cecsmsserve.util.VerificationCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 王郝浠
 * @since 2024-04-15
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    private static Map<String,String> CODE_MAP=new HashMap<>();

    @Autowired
    IUserService service;

    //注册
    @PutMapping("/register")
    public CommonResult register(@RequestBody User user) {
        return service.register(user);
    }

    //获取验证码
    @GetMapping("/getVerificationCode/{key}")
    public void getVerificationCode(@PathVariable("key") String key,HttpServletRequest request, HttpServletResponse resp) throws IOException {
        VerificationCodeUtil code = new VerificationCodeUtil();
        BufferedImage image = code.getImage();
        String text = code.getText();
        CODE_MAP.put(key,text);
        System.out.println("key:"+key);
        System.out.println("text:"+text);
        System.out.println("code:"+CODE_MAP.get(key));
//        HttpSession session = request.getSession(true);
//        session.setAttribute("verify_code", text);
//        System.out.println("session111:"+session);
//        System.out.println("verify_code111:"+session.getAttribute("verify_code"));
        VerificationCodeUtil.output(image,resp.getOutputStream());
    }

    //登录
    @PostMapping ("/login/{key}")
    public CommonResult login(@PathVariable("key") String key,@RequestParam String loginName,@RequestParam String password, String code, HttpServletRequest request, HttpServletResponse resp) throws UnsupportedEncodingException {
//        String session_code = (String) session.getAttribute("verify_code");
//        System.out.println("session222:"+session);
//        System.out.println("verify_code222:"+session_code);
//        // 首先检查验证码是否正确(不区分大小写)
//        if(!session_code.equalsIgnoreCase(code)) {
//            return new CommonResult(108,"验证码错误",null);
//        }
//        CommonResult result=new CommonResult();

//        if(request.getSession(true).getAttribute("verify_code")==null||!code.toUpperCase().equals(request.getSession(true).getAttribute("verify_code").toString().toUpperCase())){
//            return new CommonResult(107,"验证码错误",null);
//        }
        //判断验证码对不对
        System.out.println("code111:"+CODE_MAP.get(key));
        System.out.println("key222:"+key);
        System.out.println("code222:"+code);
        System.out.println("是否相等？"+code.equalsIgnoreCase(CODE_MAP.get(key)));
        if(!code.equalsIgnoreCase(CODE_MAP.get(key))){
            //如果不相等，说明验证失败
            return new CommonResult(108,"验证码错误",null);
        }
        return service.login(loginName,password);
    }

    @PutMapping("/insert")
    public CommonResult insert(@RequestBody User user){
        return service.insert(user);
    }

    //修改个人信息
    @PostMapping("/update")
    public CommonResult update(@RequestBody User user){
        return service.update(user);
    }

    @GetMapping("/selectByUsername/{username}")
    public CommonResult selectByUsername(@PathVariable String username){
        return service.selectByUsername(username);
    }

    @GetMapping("/selectByRid/{rid}")
    public CommonResult selectByRid(@PathVariable int rid){
        return service.selectByRid(rid);
    }

    @GetMapping("/selectByRidByPage/{rid}/{current}/{size}")
    public CommonResult selectByRidByPage(@PathVariable("rid")int rid,@PathVariable("current")int current,@PathVariable("size") int size){
        return service.selectByRidByPage(rid,current,size);
    }

    @GetMapping("/selectById/{id}")
    public CommonResult selectById(@PathVariable int id){
        return service.selectById(id);
    }

    @GetMapping("/selectByNameOrIdNum/{searchName}")
    public CommonResult selectByNameOrIdNum(@PathVariable String searchName){
        return service.selectByNameOrIdNum(searchName);
    }

    // 获取待审核用户列表
    @GetMapping("/pending-audit")
    public CommonResult getPendingAuditUsers() {
        return service.getPendingAuditUsers();
    }
    
    // 审核用户
    @PostMapping("/audit/{userId}")
    public CommonResult auditUser(
            @PathVariable Integer userId,
            @RequestParam Integer auditStatus,
            @RequestParam(required = false) String auditRemark) {
        return service.auditUser(userId, auditStatus, auditRemark);
    }

    @GetMapping("/selectPending")
    public CommonResult getPendingUsers(@RequestParam(defaultValue = "1") int current,
                                      @RequestParam(defaultValue = "10") int size) {
        return service.getPendingUsers(current, size);
    }

    @PutMapping("/approve/{id}")
    public CommonResult approveUser(@PathVariable Integer id) {
        return service.approveUser(id);
    }

    @PutMapping("/reject/{id}")
    public CommonResult rejectUser(@PathVariable Integer id) {
        return service.rejectUser(id);
    }
}
